import { ChangeDetectionStrategy } from '@angular/core';
import { LocalstorageDataManage } from './../../common/localstoreage/localstoreageDataManage';
import { AppStateService } from './../../app.chef.component';
import { Employee } from './../../models/Employee';
import { FrontStoreStock, FrontStoreStockViewModel } from './../../models/frontStoreStock';
import { employeesService } from './../../services/employee';
import { FrontStoreStocksService } from './../../services/frontStoreStocksService';
import { ChefMake } from './chefMake';
import { BaseComponent } from './../../components/baseComponent';
import { ViewChild, ChangeDetectorRef, ElementRef } from '@angular/core';
import { PagingMessage, YScrollableContainer } from './../../components/scrollable/y-scrollable-container';
import { FNCManager, KdsMessageType } from './../../common/fnc/fncManager';
import { GrowlMessageType } from './../../components/messageBox/growMeaageType';
import { Observable, Subject, Subscription } from 'rxjs';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { MessageBoxService } from "../../components/messageBox/messageBoxService";
import { delay } from "rxjs/operator/delay";
import { ConfirmMessageResult } from './../../components/messageBox/confirmMessage';
import * as moment from "moment";
import { Debounce, HandleExpectionErrorUseGrowMessage } from "../../common/decorator/index";
import * as R from "ramda";
import { Scheduler } from "rxjs/Scheduler";

@Component({
	selector: 'home',
	templateUrl: './home.component.html',
	providers: [

	],
	styleUrls: ['./home.component.scss'],
	changeDetection: ChangeDetectionStrategy.OnPush
})
export class HomeComponent extends BaseComponent implements OnInit, OnDestroy {
	@ViewChild(ChefMake)
	private chefMake: ChefMake;

	@ViewChild(YScrollableContainer)
	private yScrollableContainer: YScrollableContainer;

	private isProducing = false;
	private selectedProducer: Employee;
	private foodItem;
	private produceCount = '0';
	private prodeced: boolean = false;
	private lastFoodId = "";
	private sortByLetter = true;
	constructor(
		private element: ElementRef,
		private changeDetectorRef: ChangeDetectorRef,
		private frontStoreStocksService: FrontStoreStocksService,
		private appStateService: AppStateService
	) {
		super();
	}

	private list$: Observable<FrontStoreStockViewModel[]>;
	private producers;
	private setSort;

	async ngOnInit() {
		const product$ = this.frontStoreStocksService.getObservable();
		this.subscriptions.push(product$.debounceTime(800).subscribe(() => {
			this.yScrollableContainer && this.yScrollableContainer.childrenChanged();
		}))


		let sorter$ = Observable.create((observer) => {
			this.setSort = (name) => {
				observer.next(name)
			}
		}).do(sortname => {
			if (sortname == 'name') {
				this.sortByLetter = true;
			}
			if (sortname == 'count') {
				this.sortByLetter = false;
			}
			LocalstorageDataManage.current.setLastSort(sortname);
		}).map(sortname => {
			let sorter;
			if (sortname == 'name')
				sorter = (a, b) => a.inventory.name.localeCompare(b.inventory.name)
			if (sortname == 'count') {
				sorter = (a, b) => a.quantity - b.quantity;
			}
			return {
				type: "sorter",
				payload: sorter
			}
		}).merge(Observable.interval(60 * 1000)).scan((acc, value) => {
			if (value.type) {
				return value;
			} else {
				return acc;
			}
		}).share();
		this.list$ = product$.map(product => {
			return {
				type: "product",
				payload: product
			}
		}).merge<{ type: "product" | "sorter", payload: any }>(sorter$).scan<any>((state, action) => {
			switch (action.type) {
				case "product":
					const product = action.payload;
					if ((state && state.length) == product.length) {
						return state.map(entity => R.find(R.propEq('id', entity.id))(action.payload))
					} else {
						return action.payload;
					}
				case "sorter":
					return state.sort(action.payload)
			}
		}, []).share();
		this.subscriptions.push(this.list$.filter(list => list && list.length > 0).first().delay(1).subscribe(x => {
			this.setSort(LocalstorageDataManage.current.getLastSort() || "name");
		}))
		const employees = await employeesService.getChef();
		this.producers = employees.filter(employee => employee.user);
	}


	private calcTimeoutByElapsedTime(elapsedTime: number) {
		const addClass = "timeout";
		const orderConfig = LocalstorageDataManage.current.getOrderConfig();
		const timeout = orderConfig.timeoutTiming * 60;
		const isOpenSound = orderConfig.isOpenTimeoutSound;
		if (elapsedTime > timeout) {
			return addClass;
		}
	}

	pagingInfo: PagingMessage
	pagingMessageChange(event) {
		this.appStateService.changePagingInfo(event);
	}

	ngAfterViewInit() {

	}

	@HandleExpectionErrorUseGrowMessage()
	async soldOut(item) {
		const result = await MessageBoxService.current.Show("卖完沽清 " + item.inventory.name, item.inventory.name + "库存余量为" + item.quantity + "，确认卖完后沽清？");
		if (result == ConfirmMessageResult.Ok) {
			let r = await this.frontStoreStocksService.setSoldOutById(item.inventoryId);

		}
	}

	@HandleExpectionErrorUseGrowMessage()
	async cancleSoldOut(item) {
		const result = await MessageBoxService.current.Show("取消卖完沽清 " + item.inventory.name, "确认取消卖完沽清？");
		if (result == ConfirmMessageResult.Ok) {
			let r = await this.frontStoreStocksService.cancelSoldOutById(item.inventoryId);
		}
	}

	async produce(item) {
		this.foodItem = item;
		this.isProducing = true;
		let lastProduceRecord = LocalstorageDataManage.current.getLastProduceRecord();
		if (lastProduceRecord) {
			this.selectedProducer = lastProduceRecord.selectedProducer;
			if (item.inventory.id == lastProduceRecord.lastFoodId) {
				this.produceCount = lastProduceRecord.produceCount;
			} else {
				this.produceCount = "0";
			}
		}
		item.beginTime = new Date().getTime();
	}

	async closeProduce($event) {
		this.isProducing = $event.isProducing;
		this.selectedProducer = $event.selectedProducer;
		this.lastFoodId = $event.produceItem.inventory.id;
		this.produceCount = $event.produceCount;
		this.prodeced = $event.produced;
		if ($event.produced) {
			let id = $event.produceItem.id;
			let inventory = $event.produceItem.inventory;
			let quantity = +$event.produceCount;
			let producer = {
				id: $event.selectedProducer && $event.selectedProducer.user.id,
				name: $event.selectedProducer && $event.selectedProducer.user.name
			}
			let beginTime = $event.produceItem.beginTime;
			let endTime = $event.produceItem.endTime;
			this.produceCount = '0';
			await this.frontStoreStocksService.augmentFrontStoreStock(id, inventory, quantity, producer, beginTime, endTime);
		}
		let lastProduceRecord = {
			lastFoodId: this.lastFoodId,
			produceCount: this.produceCount,
			selectedProducer: this.selectedProducer
		}
		LocalstorageDataManage.current.setLastProduceRecord(lastProduceRecord);
	}
	sortByCount() {
		if (this.sortByLetter) {
			this.sortByLetter = false;
		}
		this.list$.map(items => items.sort((a, b) => a.quantity - b.quantity));
	}
}